// parser/parser.rs

use crate::model::{Token, TokenKind, AstNode};

// 语法分析结果
#[derive(Debug)]
pub enum SyntaxResult {
    Ok { ast: AstNode },
    Err { error_indices: Vec<usize> },
}

impl SyntaxResult {
    pub fn is_ok(&self) -> bool {
        matches!(self, SyntaxResult::Ok { .. })
    }

    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }
}

pub struct Parser {
    tokens: Vec<Token>,
    pos: usize,
    errors: Vec<usize>, // 收集错误 token 的索引
}

impl Parser {
    pub fn new(tokens: Vec<Token>) -> Self {
        Parser {
            tokens,
            pos: 0,
            errors: vec![],
        }
    }

    /// 主入口：解析整个编译单元
    pub fn parse(mut self) -> SyntaxResult {
        match self.parse_comp_unit() {
            Ok(ast) => {
                // 如果有错误，返回错误而不是Ok
                if self.errors.is_empty() {
                    SyntaxResult::Ok { ast }
                } else {
                    SyntaxResult::Err {
                        error_indices: self.errors,
                    }
                }
            }
            Err(()) => {
                // 如果解析失败，返回所有错误
                SyntaxResult::Err {
                    error_indices: self.errors,
                }
            }
        }
    }

    /// CompUnit → [ CompUnit ] ( Decl | FuncDef )
    fn parse_comp_unit(&mut self) -> Result<AstNode, ()> {
        let mut items = vec![];
        while self.pos < self.tokens.len() {
            let _start_pos = self.pos;
            if self.at(TokenKind::Const) || 
               (self.at(TokenKind::Int) && self.lookahead_is_decl()) {
                items.push(self.parse_decl()?);
            } else if self.lookahead_is_func_def() {
                items.push(self.parse_func_def()?);
            } else {
                // 特殊处理不完整的数组声明情况
                if self.at(TokenKind::Int) {
                    // 检查是否是 int Ident '[' ']' 模式
            if self.pos + 3 < self.tokens.len()
                && self.tokens[self.pos + 1].kind == TokenKind::Ident
                && self.tokens[self.pos + 2].kind == TokenKind::LBrack
                && self.tokens[self.pos + 3].kind == TokenKind::RBrack {
                        // 错误位置应该是 RBrack 的位置
                        self.errors.push(self.pos + 3);
                        // 跳过整个声明
                        self.pos += 4; // 跳过 Int, Ident, LBrack, RBrack
                        if self.pos < self.tokens.len() && self.tokens[self.pos].kind == TokenKind::Semicolon {
                            self.pos += 1; // 跳过分号
                        }
                        continue;
                    }
                }
                // 错误：既不是声明也不是函数定义
                self.errors.push(self.pos);
                self.recover_to_next_top_level();
            }
        }
        Ok(AstNode::Sequence(items))
    }

    /// Decl → ConstDecl | VarDecl
    fn parse_decl(&mut self) -> Result<AstNode, ()> {
        if self.at(TokenKind::Const) {
            self.parse_const_decl()
        } else {
            self.parse_var_decl()
        }
    }

    /// ConstDecl → 'const' BType ConstDef {',' ConstDef} ';'
    fn parse_const_decl(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        self.consume(TokenKind::Const); // 消费 'const'
        children.push(AstNode::Token(TokenKind::Const, Some("const".to_string())));
        
        // BType 必须是 'int'
        self.expect(TokenKind::Int)?;
        children.push(AstNode::Token(TokenKind::Int, Some("int".to_string())));

        // 解析至少一个 ConstDef
        let def = self.parse_const_def()?;
        children.push(def);
        // 解析后续的 ',' ConstDef
        while self.consume(TokenKind::Comma) {
            children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
            let def = self.parse_const_def()?;
            children.push(def);
        }
        // 必须以 ';' 结束
        self.expect(TokenKind::Semicolon)?;
        children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));

        Ok(AstNode::Node {
            kind: TokenKind::Const,
            children,
            token_start_idx: start_pos,
        })
    }

    /// ConstDef → Ident {'[' ConstExp ']'} '=' ConstInitVal
    fn parse_const_def(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        // Ident
        self.expect(TokenKind::Ident)?;
        children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));

        // {'[' ConstExp ']'}
        while self.consume(TokenKind::LBrack) {
            children.push(AstNode::Token(TokenKind::LBrack, Some("[".to_string())));
            let exp = self.parse_const_exp()?;
            children.push(exp);
            self.expect(TokenKind::RBrack)?;
            children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
        }

        // '='
        self.expect(TokenKind::Assign)?;
        children.push(AstNode::Token(TokenKind::Assign, Some("=".to_string())));
        
        // ConstInitVal
        let init_val = self.parse_const_init_val()?;
        children.push(init_val);

        Ok(AstNode::Node {
            kind: TokenKind::Ident,
            children,
            token_start_idx: start_pos,
        })
    }

    /// ConstInitVal → ConstExp | '{' [ ConstInitVal {',' ConstInitVal} ] '}'
    fn parse_const_init_val(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        if self.at(TokenKind::LBrace) {
            let mut children = vec![AstNode::Token(TokenKind::LBrace, Some("{".to_string()))];
            self.consume(TokenKind::LBrace); // 消费 '{'
            
            // 解析初始化值列表（可选）
            if !self.at(TokenKind::RBrace) {
                let init_val = self.parse_const_init_val()?;
                children.push(init_val);
                while self.consume(TokenKind::Comma) {
                    children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
                    let init_val = self.parse_const_init_val()?;
                    children.push(init_val);
                }
            }
            
            self.expect(TokenKind::RBrace)?;
            children.push(AstNode::Token(TokenKind::RBrace, Some("}".to_string())));
            
            Ok(AstNode::Node {
                kind: TokenKind::LBrace,
                children,
                token_start_idx: start_pos,
            })
        } else {
            // ConstExp
            self.parse_const_exp()
        }
    }

    /// VarDecl → BType VarDef {',' VarDef} ';'
    fn parse_var_decl(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        // BType 必须是 'int'
        self.expect(TokenKind::Int)?;
        children.push(AstNode::Token(TokenKind::Int, Some("int".to_string())));

        // 解析至少一个 VarDef
        let def = self.parse_var_def()?;
        children.push(def);
        // 解析后续的 ',' VarDef
        while self.consume(TokenKind::Comma) {
            children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
            let def = self.parse_var_def()?;
            children.push(def);
        }
        // 必须以 ';' 结束
        self.expect(TokenKind::Semicolon)?;
        children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));

        Ok(AstNode::Node {
            kind: TokenKind::Int,
            children,
            token_start_idx: start_pos,
        })
    }

    /// VarDef → Ident {'[' ConstExp ']'} | Ident {'[' ConstExp ']'} '=' InitVal
    fn parse_var_def(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        // Ident
        self.expect(TokenKind::Ident)?;
        children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));

        // {'[' ConstExp ']'}
        while self.consume(TokenKind::LBrack) {
            children.push(AstNode::Token(TokenKind::LBrack, Some("[".to_string())));
            // 检查是否为空数组声明（缺少大小）
            if self.at(TokenKind::RBrack) {
                // 空数组声明是错误的，但我们可以记录错误并继续
                self.errors.push(self.pos);
                // 跳过右括号
                self.pos += 1;
                children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
                continue;
            }
            
            let exp = self.parse_const_exp()?;
            children.push(exp);
            self.expect(TokenKind::RBrack)?;
            children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
        }

        // '=' InitVal (可选)
        if self.at(TokenKind::Assign) {
            self.consume(TokenKind::Assign);
            children.push(AstNode::Token(TokenKind::Assign, Some("=".to_string())));
            let init_val = self.parse_init_val()?;
            children.push(init_val);
        }

        Ok(AstNode::Node {
            kind: TokenKind::Ident,
            children,
            token_start_idx: start_pos,
        })
    }

    /// InitVal → Exp | '{' [ InitVal {',' InitVal} ] '}'
    fn parse_init_val(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        if self.at(TokenKind::LBrace) {
            let mut children = vec![AstNode::Token(TokenKind::LBrace, Some("{".to_string()))];
            self.consume(TokenKind::LBrace); // 消费 '{'
            
            // 解析初始化值列表（可选）
            if !self.at(TokenKind::RBrace) {
                let init_val = self.parse_init_val()?;
                children.push(init_val);
                while self.consume(TokenKind::Comma) {
                    children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
                    let init_val = self.parse_init_val()?;
                    children.push(init_val);
                }
            }
            
            self.expect(TokenKind::RBrace)?;
            children.push(AstNode::Token(TokenKind::RBrace, Some("}".to_string())));
            
            Ok(AstNode::Node {
                kind: TokenKind::LBrace,
                children,
                token_start_idx: start_pos,
            })
        } else {
            // Exp
            self.parse_exp()
        }
    }

    /// FuncDef → FuncType Ident '(' [FuncFParams] ')' Block
    fn parse_func_def(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        // FuncType
        let func_type = if self.consume(TokenKind::Void) {
            children.push(AstNode::Token(TokenKind::Void, Some("void".to_string())));
            TokenKind::Void
        } else {
            self.expect(TokenKind::Int)?;
            children.push(AstNode::Token(TokenKind::Int, Some("int".to_string())));
            TokenKind::Int
        };

        // Ident
        self.expect(TokenKind::Ident)?;
        children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));

        // '('
        self.expect(TokenKind::LParen)?;
        children.push(AstNode::Token(TokenKind::LParen, Some("(".to_string())));

        // [FuncFParams]
        if !self.at(TokenKind::RParen) {
            let params = self.parse_func_fparams()?;
            children.push(params);
        }

        // ')'
        self.expect(TokenKind::RParen)?;
        children.push(AstNode::Token(TokenKind::RParen, Some(")".to_string())));

        // Block
        let block = self.parse_block()?;
        children.push(block);

        Ok(AstNode::Node {
            kind: func_type, // 用返回类型标记函数节点
            children,
            token_start_idx: start_pos,
        })
    }

    /// FuncFParams → FuncFParam {',' FuncFParam}
    fn parse_func_fparams(&mut self) -> Result<AstNode, ()> {
        let mut children = vec![];
        let param = self.parse_func_fparam()?;
        children.push(param);
        while self.consume(TokenKind::Comma) {
            children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
            let param = self.parse_func_fparam()?;
            children.push(param);
        }
        Ok(AstNode::Sequence(children))
    }

    /// FuncFParam → BType Ident ['['']' {'[' Exp ']'}]
    fn parse_func_fparam(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        // BType
        self.expect(TokenKind::Int)?;
        children.push(AstNode::Token(TokenKind::Int, Some("int".to_string())));

        // Ident
        self.expect(TokenKind::Ident)?;
        children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));

        // ['['']' ...]
        if self.consume(TokenKind::LBrack) {
            children.push(AstNode::Token(TokenKind::LBrack, Some("[".to_string())));
            self.expect(TokenKind::RBrack)?;
            children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
            // {'[' Exp ']'}
            while self.at(TokenKind::LBrack) {
                self.consume(TokenKind::LBrack);
                children.push(AstNode::Token(TokenKind::LBrack, Some("[".to_string())));
                let exp = self.parse_exp()?;
                children.push(exp);
                self.expect(TokenKind::RBrack)?;
                children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
            }
        }

        Ok(AstNode::Node {
            kind: TokenKind::Int,
            children,
            token_start_idx: start_pos,
        })
    }

    /// Block → '{' { BlockItem } '}'
    fn parse_block(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        self.expect(TokenKind::LBrace)?;
        children.push(AstNode::Token(TokenKind::LBrace, Some("{".to_string())));

        while !self.at(TokenKind::RBrace) && self.pos < self.tokens.len() {
            let item = self.parse_block_item()?;
            children.push(item);
        }

        self.expect(TokenKind::RBrace)?;
        children.push(AstNode::Token(TokenKind::RBrace, Some("}".to_string())));

        Ok(AstNode::Node {
            kind: TokenKind::LBrace,
            children,
            token_start_idx: start_pos,
        })
    }

    /// BlockItem → Decl | Stmt
    fn parse_block_item(&mut self) -> Result<AstNode, ()> {
        // 检查是否为声明 (ConstDecl 或 VarDecl)
        if self.at(TokenKind::Const) || 
           (self.at(TokenKind::Int) && self.lookahead_is_decl_in_block()) {
            self.parse_decl()
        } else {
            // 否则解析为语句
            self.parse_stmt()
        }
    }

    /// Stmt → LVal '=' Exp ';' | [Exp] ';' | Block | 'if' '(' Cond ')' Stmt ['else' Stmt]
    ///       | 'while' '(' Cond ')' Stmt | 'break' ';' | 'continue' ';' | 'return' [Exp] ';'
    fn parse_stmt(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];

        match self.tokens.get(self.pos).map(|t| t.kind) {
            Some(TokenKind::If) => {
                self.consume(TokenKind::If);
                children.push(AstNode::Token(TokenKind::If, Some("if".to_string())));
                self.expect(TokenKind::LParen)?;
                children.push(AstNode::Token(TokenKind::LParen, Some("(".to_string())));
                let cond = self.parse_cond()?;
                children.push(cond);
                self.expect(TokenKind::RParen)?;
                children.push(AstNode::Token(TokenKind::RParen, Some(")".to_string())));
                let stmt = self.parse_stmt()?;
                children.push(stmt);
                if self.consume(TokenKind::Else) {
                    children.push(AstNode::Token(TokenKind::Else, Some("else".to_string())));
                    let else_stmt = self.parse_stmt()?;
                    children.push(else_stmt);
                }
            }
            Some(TokenKind::While) => {
                self.consume(TokenKind::While);
                children.push(AstNode::Token(TokenKind::While, Some("while".to_string())));
                self.expect(TokenKind::LParen)?;
                children.push(AstNode::Token(TokenKind::LParen, Some("(".to_string())));
                let cond = self.parse_cond()?;
                children.push(cond);
                self.expect(TokenKind::RParen)?;
                children.push(AstNode::Token(TokenKind::RParen, Some(")".to_string())));
                let stmt = self.parse_stmt()?;
                children.push(stmt);
            }
            Some(TokenKind::Break) => {
                self.consume(TokenKind::Break);
                children.push(AstNode::Token(TokenKind::Break, Some("break".to_string())));
                self.expect(TokenKind::Semicolon)?;
                children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));
            }
            Some(TokenKind::Continue) => {
                self.consume(TokenKind::Continue);
                children.push(AstNode::Token(TokenKind::Continue, Some("continue".to_string())));
                self.expect(TokenKind::Semicolon)?;
                children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));
            }
            Some(TokenKind::Return) => {
                self.consume(TokenKind::Return);
                children.push(AstNode::Token(TokenKind::Return, Some("return".to_string())));
                if !self.at(TokenKind::Semicolon) {
                    let exp = self.parse_exp()?;
                    children.push(exp);
                }
                self.expect(TokenKind::Semicolon)?;
                children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));
            }
            Some(TokenKind::LBrace) => {
                return self.parse_block();
            }
            _ => {
                // LVal '=' Exp ';' 或 [Exp] ';'
                if self.at(TokenKind::Ident) && self.lookahead_is_assignment() {
                    // LVal '=' Exp ';'
                    let lval = self.parse_lval();
                    match lval {
                        Ok(l) => children.push(l),
                        Err(_) => {
                            self.recover_to_next_stmt();
                            return Err(());
                        }
                    }
                    
                    if !self.consume(TokenKind::Assign) {
                        self.errors.push(self.pos);
                        self.recover_to_next_stmt();
                        return Err(());
                    }
                    children.push(AstNode::Token(TokenKind::Assign, Some("=".to_string())));
                    
                    let exp = self.parse_exp();
                    match exp {
                        Ok(e) => children.push(e),
                        Err(_) => {
                            self.recover_to_next_stmt();
                            return Err(());
                        }
                    }
                    
                    if !self.consume(TokenKind::Semicolon) {
                        self.errors.push(self.pos);
                        self.recover_to_next_stmt();
                        return Err(());
                    }
                    children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));
                } else {
                    // [Exp] ';'
                    if !self.at(TokenKind::Semicolon) {
                        let exp = self.parse_exp();
                        match exp {
                            Ok(e) => children.push(e),
                            Err(_) => {
                                self.recover_to_next_stmt();
                                return Err(());
                            }
                        }
                    }
                    
                    if !self.consume(TokenKind::Semicolon) {
                        self.errors.push(self.pos);
                        self.recover_to_next_stmt();
                        return Err(());
                    }
                    children.push(AstNode::Token(TokenKind::Semicolon, Some(";".to_string())));
                }
            }
        }

        Ok(AstNode::Node {
            kind: match &children[0] {
                AstNode::Token(kind, _) => *kind,
                AstNode::Node { kind, .. } => *kind,
                AstNode::Sequence(_) => TokenKind::LBrace, // 默认值
            },
            children,
            token_start_idx: start_pos,
        })
    }

    /// LVal → Ident {'[' Exp ']'}
    fn parse_lval(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut children = vec![];
        self.expect(TokenKind::Ident)?;
        children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));
        while self.consume(TokenKind::LBrack) {
            children.push(AstNode::Token(TokenKind::LBrack, Some("[".to_string())));
            let exp = self.parse_exp()?;
            children.push(exp);
            self.expect(TokenKind::RBrack)?;
            children.push(AstNode::Token(TokenKind::RBrack, Some("]".to_string())));
        }
        Ok(AstNode::Node {
            kind: TokenKind::Ident,
            children,
            token_start_idx: start_pos,
        })
    }

    /// Exp → AddExp
    fn parse_exp(&mut self) -> Result<AstNode, ()> {
        self.parse_add_exp()
    }

    /// Cond → LOrExp
    fn parse_cond(&mut self) -> Result<AstNode, ()> {
        self.parse_lor_exp()
    }

    // ------------------- 表达式解析 (优先级递归下降) -------------------

    /// AddExp → MulExp | AddExp ('+' | '−') MulExp
    fn parse_add_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_mul_exp()?;
        while self.at(TokenKind::Plus) || self.at(TokenKind::Minus) {
            let op = self.tokens[self.pos].kind;
            self.pos += 1;
            let right = self.parse_mul_exp()?;
            left = AstNode::Node {
                kind: op,
                children: vec![left, AstNode::Token(op, Some(self.tokens[self.pos - 1].text.clone())), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// MulExp → UnaryExp | MulExp ('*' | '/' | '%') UnaryExp
    fn parse_mul_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_unary_exp()?;
        while self.current_is_mul_op() {
            let op = self.tokens[self.pos].kind;
            self.pos += 1;
            let right = self.parse_unary_exp()?;
            left = AstNode::Node {
                kind: op,
                children: vec![left, AstNode::Token(op, Some(self.tokens[self.pos - 1].text.clone())), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// UnaryExp → PrimaryExp | Ident '(' [FuncRParams] ')' | UnaryOp UnaryExp
    fn parse_unary_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        // UnaryOp
        if self.current_is_unary_op() {
            let op = self.tokens[self.pos].kind;
            self.pos += 1;
            let expr = self.parse_unary_exp()?; // 递归，保证右结合
            return Ok(AstNode::Node {
                kind: op,
                children: vec![AstNode::Token(op, Some(self.tokens[self.pos - 1].text.clone())), expr],
                token_start_idx: start_pos,
            });
        }

        // Function Call: Ident '(' ...
        if self.at(TokenKind::Ident) && self.lookahead_is_func_call() {
            let mut children = vec![];
            self.consume(TokenKind::Ident);
            children.push(AstNode::Token(TokenKind::Ident, Some(self.tokens[self.pos - 1].text.clone())));
            self.expect(TokenKind::LParen)?;
            children.push(AstNode::Token(TokenKind::LParen, Some("(".to_string())));
            if !self.at(TokenKind::RParen) {
                let args = self.parse_func_rparams()?;
                children.push(args);
            }
            self.expect(TokenKind::RParen)?;
            children.push(AstNode::Token(TokenKind::RParen, Some(")".to_string())));
            return Ok(AstNode::Node {
                kind: TokenKind::Ident, // 标记为函数调用
                children,
                token_start_idx: start_pos,
            });
        }

        // PrimaryExp
        self.parse_primary_exp()
    }

    /// PrimaryExp → '(' Exp ')' | LVal | Number
    fn parse_primary_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        if self.consume(TokenKind::LParen) {
            let exp = self.parse_exp()?;
            self.expect(TokenKind::RParen)?;
            Ok(AstNode::Node {
                kind: TokenKind::LParen,
                children: vec![
                    AstNode::Token(TokenKind::LParen, Some("(".to_string())),
                    exp,
                    AstNode::Token(TokenKind::RParen, Some(")".to_string())),
                ],
                token_start_idx: start_pos,
            })
        } else if self.at(TokenKind::Ident) {
            self.parse_lval() // LVal
        } else if self.at(TokenKind::IntegerConst) {
            // 检查后面是否紧跟着数字或字母，这可能意味着前面的数字常量是无效的
            let _integer_pos = self.pos;
            let integer_text = self.tokens[self.pos].text.clone();
            self.consume(TokenKind::IntegerConst);
            
                // 检查下一个标记是否是数字或字母，这可能意味着当前数字是无效数字序列的一部分
                if self.pos < self.tokens.len() {
                    match self.tokens[self.pos].kind {
                        TokenKind::IntegerConst | TokenKind::Ident => {
                            // 这很可能是一个无效的数字序列，报告错误
                            self.errors.push(self.pos);
                            // 跳过这个标记以继续解析
                            self.pos += 1;
                        }
                        _ => {}
                    }
                }
            
            Ok(AstNode::Token(TokenKind::IntegerConst, Some(integer_text)))
        } else {
            self.errors.push(self.pos);
            Err(())
        }
    }

    /// FuncRParams → Exp {',' Exp}
    fn parse_func_rparams(&mut self) -> Result<AstNode, ()> {
        let mut children = vec![];
        let exp = self.parse_exp()?;
        children.push(exp);
        while self.consume(TokenKind::Comma) {
            children.push(AstNode::Token(TokenKind::Comma, Some(",".to_string())));
            let exp = self.parse_exp()?;
            children.push(exp);
        }
        Ok(AstNode::Sequence(children))
    }

    // LOrExp, LAndExp, EqExp, RelExp 结构与 AddExp 类似，省略...

    /// LOrExp → LAndExp | LOrExp '||' LAndExp
    fn parse_lor_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_land_exp()?;
        while self.at(TokenKind::Or) {
            let op_text = self.tokens[self.pos].text.clone();
            self.consume(TokenKind::Or);
            let right = self.parse_land_exp()?;
            left = AstNode::Node {
                kind: TokenKind::Or,
                children: vec![left, AstNode::Token(TokenKind::Or, Some(op_text)), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// LAndExp → EqExp | LAndExp '&&' EqExp
    fn parse_land_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_eq_exp()?;
        while self.at(TokenKind::And) {
            let op_text = self.tokens[self.pos].text.clone();
            self.consume(TokenKind::And);
            let right = self.parse_eq_exp()?;
            left = AstNode::Node {
                kind: TokenKind::And,
                children: vec![left, AstNode::Token(TokenKind::And, Some(op_text)), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// EqExp → RelExp | EqExp ('==' | '!=') RelExp
    fn parse_eq_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_rel_exp()?;
        while self.at(TokenKind::Eq) || self.at(TokenKind::Neq) {
            let op = self.tokens[self.pos].kind;
            let op_text = self.tokens[self.pos].text.clone();
            self.pos += 1;
            let right = self.parse_rel_exp()?;
            left = AstNode::Node {
                kind: op,
                children: vec![left, AstNode::Token(op, Some(op_text)), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// RelExp → AddExp | RelExp ('<' | '>' | '<=' | '>=') AddExp
    fn parse_rel_exp(&mut self) -> Result<AstNode, ()> {
        let start_pos = self.pos; // 记录起始位置
        let mut left = self.parse_add_exp()?;
        while self.current_is_rel_op() {
            let op = self.tokens[self.pos].kind;
            let op_text = self.tokens[self.pos].text.clone();
            self.pos += 1;
            let right = self.parse_add_exp()?;
            left = AstNode::Node {
                kind: op,
                children: vec![left, AstNode::Token(op, Some(op_text)), right],
                token_start_idx: start_pos,
            };
        }
        Ok(left)
    }

    /// ConstExp → AddExp
    fn parse_const_exp(&mut self) -> Result<AstNode, ()> {
        self.parse_add_exp() // 与 AddExp 相同，但语义检查时会限制 Ident 必须是常量
    }

    // ------------------- 辅助方法 -------------------

    fn at(&self, kind: TokenKind) -> bool {
        self.tokens.get(self.pos).map(|t| t.kind) == Some(kind)
    }

    fn consume(&mut self, kind: TokenKind) -> bool {
        if self.at(kind) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn expect(&mut self, kind: TokenKind) -> Result<(), ()> {
        if self.consume(kind) {
            Ok(())
        } else {
            self.errors.push(self.pos);
            Err(())
        }
    }

    fn current_is_unary_op(&self) -> bool {
        matches!(
            self.tokens.get(self.pos).map(|t| t.kind),
            Some(TokenKind::Plus | TokenKind::Minus | TokenKind::Not)
        )
    }

    fn current_is_mul_op(&self) -> bool {
        matches!(
            self.tokens.get(self.pos).map(|t| t.kind),
            Some(TokenKind::Mul | TokenKind::Div | TokenKind::Mod)
        )
    }

    fn current_is_rel_op(&self) -> bool {
        matches!(
            self.tokens.get(self.pos).map(|t| t.kind),
            Some(TokenKind::Lt | TokenKind::Gt | TokenKind::Le | TokenKind::Ge)
        )
    }

    fn lookahead_is_decl(&self) -> bool {
        if self.at(TokenKind::Const) {
            return true;
        }
        
        if self.at(TokenKind::Int) {
            if let Some(next) = self.tokens.get(self.pos + 1) {
                // 检查是否是标识符，并且下一个标记不是 '('，以区分函数定义
                if matches!(next.kind, TokenKind::Ident) 
                    && (self.pos + 2 >= self.tokens.len() || self.tokens[self.pos + 2].kind != TokenKind::LParen) {
                    // 即使是空数组声明 int Ident []，也应该被视为声明（虽然语法错误）
                    // 让解析器在parse_var_def中处理具体的错误
                    return true;
                }
            }
        }
        false
    }

    fn lookahead_is_decl_in_block(&self) -> bool {
        // 在块内，声明必须是 Const 或 Int Ident (但不是函数定义)
        if self.at(TokenKind::Const) {
            return true;
        }
        
        if self.at(TokenKind::Int) {
            // 检查下一个标记是否为标识符，且不是函数定义
            if let Some(next) = self.tokens.get(self.pos + 1) {
                return matches!(next.kind, TokenKind::Ident) 
                    && (self.pos + 2 >= self.tokens.len() || self.tokens[self.pos + 2].kind != TokenKind::LParen);
            }
        }
        
        false
    }

    fn lookahead_is_assignment(&self) -> bool {
        // Ident 后跟 '[' 或 '='
        if self.at(TokenKind::Ident) {
            let mut i = self.pos + 1;
            while i < self.tokens.len() && self.tokens[i].kind == TokenKind::LBrack {
                // 跳过 [ Exp ]
                i += 1;
                // 这里应该解析 Exp，但为简化，我们只检查结构
                // 在实际中，你需要一个更复杂的前瞻
                while i < self.tokens.len() && self.tokens[i].kind != TokenKind::RBrack {
                    i += 1;
                }
                if i < self.tokens.len() {
                    i += 1; // 跳过 RBrack
                }
            }
            return i < self.tokens.len() && self.tokens[i].kind == TokenKind::Assign;
        }
        false
    }

    fn lookahead_is_func_call(&self) -> bool {
        self.pos + 1 < self.tokens.len() && self.tokens[self.pos + 1].kind == TokenKind::LParen
    }

    fn lookahead_is_func_def(&self) -> bool {
        // 检查是否是函数定义: (Void | Int) Ident '('
        if self.at(TokenKind::Void) {
            // void Ident (
            return self.pos + 2 < self.tokens.len()
                && self.tokens[self.pos + 1].kind == TokenKind::Ident
                && self.tokens[self.pos + 2].kind == TokenKind::LParen;
        } else if self.at(TokenKind::Int) {
            // int Ident ( - 这一定是函数定义
            // 或者 int Ident [ - 这可能是数组声明或函数参数
            if self.pos + 2 < self.tokens.len() {
                if self.tokens[self.pos + 1].kind == TokenKind::Ident {
                    if self.tokens[self.pos + 2].kind == TokenKind::LParen {
                        return true; // int Ident ( - 函数定义
                    }
                    // 检查是否是函数参数中的数组类型
                    if self.tokens[self.pos + 2].kind == TokenKind::LBrack {
                        // 进一步检查后面是否有右括号和左括号
                        if self.pos + 4 < self.tokens.len() {
                            return self.tokens[self.pos + 3].kind == TokenKind::RBrack
                                && self.tokens[self.pos + 4].kind == TokenKind::LParen;
                        }
                    }
                }
            }
        }
        false
    }

    fn recover_to_next_top_level(&mut self) {
        while self.pos < self.tokens.len() {
            match self.tokens[self.pos].kind {
                TokenKind::Const | TokenKind::Int | TokenKind::Void => {
                    // 下一个顶层项
                    if self.lookahead_is_func_def() || self.lookahead_is_decl() {
                        return;
                    }
                }
                TokenKind::Semicolon => {
                    self.pos += 1;
                    return;
                }
                TokenKind::LBrace => {
                    self.skip_block();
                    return;
                }
                _ => {}
            }
            self.pos += 1;
        }
    }

    fn recover_to_next_stmt(&mut self) {
        while self.pos < self.tokens.len() && !self.at(TokenKind::Semicolon) {
            self.pos += 1;
        }
        if self.pos < self.tokens.len() && self.at(TokenKind::Semicolon) {
            self.pos += 1; // 跳过分号
        }
    }

    fn skip_block(&mut self) {
        let mut depth = 0;
        while self.pos < self.tokens.len() {
            match self.tokens[self.pos].kind {
                TokenKind::LBrace => depth += 1,
                TokenKind::RBrace => {
                    depth -= 1;
                    if depth == 0 {
                        self.pos += 1;
                        return;
                    }
                }
                _ => {}
            }
            self.pos += 1;
        }
    }

    fn has_main_function(&self, ast: &AstNode) -> bool {
        // 检查是否存在 main 函数
        // 注意：这是一个简化的实现，实际应进行更严格的检查
        if let AstNode::Sequence(items) = ast {
            for item in items {
                if let AstNode::Node { kind: TokenKind::Int, children, .. } = item {
                    // 简单检查函数定义结构
                    if children.len() >= 5 {
                        if let AstNode::Token(kind, _) = &children[1] {
                            if *kind == TokenKind::Ident {
                                if let AstNode::Token(kind, _) = &children[2] {
                                    if *kind == TokenKind::LParen {
                                        if let AstNode::Token(kind, _) = &children[3] {
                                            if *kind == TokenKind::RParen {
                                                return true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        false
    }
}

// 为 AstNode 实现一个便捷方法
impl AstNode {
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_input() {
        let tokens = vec![];
        let parser = Parser::new(tokens);
        let result = parser.parse();
        assert!(result.is_err());
    }

    #[test]
    fn test_simple_int_decl() {
        let tokens = vec![
            Token { line: 1, kind: TokenKind::Int, text: "int".to_string() },
            Token { line: 1, kind: TokenKind::Ident, text: "x".to_string() },
            Token { line: 1, kind: TokenKind::Semicolon, text: ";".to_string() },
        ];
        let parser = Parser::new(tokens);
        let result = parser.parse();
        assert!(result.is_err()); // 由于没有main函数，应该返回错误
    }
}
